<?php
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

global $_LV;
//加载缓存

function unserialize_fielddata($ufielddata){
	global $_G;
	$data = '';
	foreach(unserialize($ufielddata) as $k=>$fieldid) {
		$data .= '<li>'.$_G['cache']['profilesetting'][$k]['title'].'&nbsp;&nbsp;:&nbsp;&nbsp;'.$fieldid.'</li>';
	}
	return $data;
}

function activity_role($id, $format){
	$all_role=array(0=>'队员', 1=>'领队', 2=>'副领队', 3=>'财务');
	if($format=='show'){
		return ' ['.$all_role[$id].']';
	} elseif($format=='list'){
		return $all_role;
	} else {
		return $all_role[$id];
	}
}

function activity_status($id, $format){
	$all_status=array(0=>'活动报名中', 1=>'未开始', 2=>'报名中', 3=>'人已满', 4=>'评论中', 5=>'时间结束', 6=>'人为取消');
	if($format=='img'){
		return '<img class="vmiddle" src="./source/plugin/donkey_activity/static/status_'.$id.'.gif" alt="'.$all_status[$id].'">';
	} else {
		return $all_status[$id];
	}
}

function apply_status($id){
	$all_status=array(0=>'待审批', 1=>'已审核', 2=>'待完善', 3=>'放鸽子', 4=>'被拒绝', 5=>'');
	return (empty($id) || $id < 0) ? $all_status : $all_status[$id];
}

function all_group(){
	$query = DB::query("SELECT groupid, grouptitle FROM ".DB::table('common_usergroup'));
	$all_group=array();
	while($group = DB::fetch($query)) {
		$all_group[$group['groupid']]=$group['grouptitle'];
	}
	return $all_group;
}

function get_gender($gender){
	if($gender == 2){
		return 'MM';
	} else if($gender == 1){
		return 'GG';
	} else {
		return '--';
	}
}

function get_activity($status='', $manager=''){
	global $_G;
	$activity = DB::fetch_first('SELECT at.uid, at.status, at.prop_3, ft.subject FROM '.DB::table('donkey_activity_thread').' at, '.DB::table('forum_thread')." ft WHERE at.tid='$_G[gp_tid]' and ft.tid='$_G[gp_tid]'");
	//判断活动是否存在
	if(empty($activity)){
		showmessage('活动不存在');
	}
	if($status === 'stop' && check_status($activity['status'], $activity['prop_3'], $_G[gp_tid])){
		showmessage('活动已经停止报名');
	}
	if($manager === 'manager' && !isactivitymaster($activity['uid'])){
		showmessage('activity_is_not_manager');
	}
	return $activity;
}

function get_prop($arr, $param){
	return empty($arr) || empty($arr[$param]) ? '---' : $arr[$param];
}

function echo_prop($arr, $param){
	echo get_prop($arr, $param)."\t";
}

//判断是否为活动管理员
function isactivitymaster($authorid){
	global $_G;
	return $authorid == $_G['uid'] || (in_array($_G['group']['radminid'], array(1, 2)) || ($_G['group']['radminid'] == 3 && $_G['forum']['ismoderator']) && $_G['group']['alloweditactivity']);
}

function activity_ufield(){
	//TODO
	$ufield = array();
	$ufield['userfield'] = array('realname', 'mobile', 'qq');
	//$ufield['extfield']
	return $ufield;
}

function check_status($status, $endtime, $tid){
	if($status == 0){
		if(strtotime($endtime) < time()){
			$status = 5;
			//TODO，update到数据库
		} else if((strtotime($endtime) - time() < 14 * 86400)){	//两周以内为评论时间
			$status = 4;
			//TODO，update到数据库
		}
	}
	
	//TODO for debug
	return 0;
	return $status;
}

function isVerify($uid_){
	global $_G;
	if(empty($uid_))$uid_=$_G['uid'];
	//refer: \source\include\spacecp\spacecp_profile.php
	//refer: \source\admincp\admincp_verify.php
	//用户填写的等待验证的认证信息保存在common_member_verify_info表中，
	//验证以后这个表里面的记录就删除了，common_member_verify标记flag为已经认证
	//认证的实际数据还是保存在用户数据表中：common_member_profile
	foreach ($_G['setting']['verify'] as $k => $v) {
		//因为系统设置了7种认证，首先判断是那一个是实名认证，admin.php?action=verify
		if(strpos($v['title'], '实名') && ($v['available'] == '1')){
			$verify = DB::fetch_first('SELECT verify'.$k.' FROM '.DB::table('common_member_verify').' WHERE uid='.$uid_);
			return $verify['verify'.$k] == 1 || $verify['verify'.$k] == '1';
		}
	}
	return false;
}

//获得页面的UI规则
function getUIRules(){
	global $_G;
	$s = 'var rules=new Array();';
	$s .= 'rules[0]=["prop_1", "eq", "2", "prop_30", "hidden"];';
	$s .= 'rules[1]=["prop_1", "eq", "2", "prop_32", "hidden"];';
	$s .= 'rules[2]=["prop_1", "eq", "2", "prop_33", "hidden"];';
	$s .= 'rules[3]=["prop_1", "eq", "2", "prop_34", "hidden"];';
	$s .= 'rules[4]=["prop_1", "eq", "2", "prop_11", "hidden"];';
	$s .= 'rules[5]=["prop_1", "eq", "2", "prop_12", "hidden"];';
	$s .= 'rules[6]=["prop_1", "eq", "2", "prop_13", "hidden"];';
	return $s;
}

//获得页面的UI合并
function getUIMerges(){
	global $_G;
	$merges=array();
	$merges['prop_2']=array('prop_2', 'prop_3', '活动时间');
	$merges['prop_4']=array('prop_4', 'prop_5', '报名时间');
	$merges['prop_14']=array('prop_14', 'prop_15', '人数限制');
	$merges['prop_35']=array('prop_35', 'prop_36', '积分奖励');
	$merges['hidden']=array('prop_3', 'prop_5', 'prop_15', 'prop_36');
	return $merges;
}

//页面上显示的用户表单数据
function get_default_value($type, $values, $defval, $userval){
	
	global $_G;
	$type=$type?trim($type):'text';
	$values=$values?trim($values):'';
	$defval=$defval?trim($defval):'';

	$s = '';
	if($type == 'text' || $type == 'password' || $type == 'number' || $type=='textarea' || $type=='date' || $type=='datetime' || $type=='city') {
		$s = empty($userval)?$values:$userval;
	} else if ($type=='richtext') {
		$val =empty($userval)?$values:$userval;
		if(!empty($val)){
			$s = '<div class="richborder">'.discuzcode($val).'</div>';
		}
	} else if ($type=='select') {
		$val = $userval;
		if(empty($val)) $val = $defval;
		foreach(explode("\n", $values) as $key => $option) {
			$option = trim($option);
			if(strpos($option, '=') === FALSE) {
				//$key = $option;
			} else {
				$item = explode('=', $option);
				$key = trim($item[0]);
				$option = trim($item[1]);
			}
			if($key == $val){
				$s = $option;
				break;
			}
		}
	} else if ($type=='credit') {
		$val = $userval;
		if(empty($val)) $val = $defval;
		foreach($_G['setting']['extcredits'] as $key => $option) {
			if($key == $val){
				$s = $option['title'];
				break;
			}
		}
	} else if ($type=='pay'){
		$s .= '线下支付';	//TODO
	} else if ($type=='leader'){
		$val = empty($userval)? $defval : $userval;
		if(!empty($val)){
			$uid=intval($val);
			if($uid>0){	//认证用户保存的是用户 id，非认证用户保存的是用户名
				$query=DB::fetch_first('SELECT uid, username FROM '.DB::table('common_member').' WHERE uid='.$uid);
				if(!empty($query)){
					$s .= '<a style="float:left;" title="认证领队: '.$query['username'].'" href="home.php?mod=space&uid='.$query['uid'].'" target="_blank"> '.avatar($query['uid'], 'small').' </a>';
					
					$s .= '<div class="leader_info"><a title="认证领队: '.$query['username'].'" href="home.php?mod=space&uid='.$query['uid'].'" target="_blank" ><img alt="认证领队" src="'.IMGDIR.'/data_valid.gif'.'"/> '.$query['username'].' </a>';
					
					$query=DB::fetch_first('SELECT mobile, qq FROM '.DB::table('common_member_profile').' WHERE uid='.$uid);
					if(!empty($query)){
						if(!empty($query['mobile'])){
							$s .= '<span><img alt="Mobile" src="'.IMGDIR.'/mobile.png'.'"/> '.$query['mobile'].'</span>';
						}
						if(!empty($query['qq'])){
							$s .= '<a href="http://wpa.qq.com/msgrd?V=1&Uin='.$query['qq'].'&Site='.$_G['setting']['bbname'].'&Menu=yes" target="_blank" title="QQ: '.$query['qq'].'"><img alt="QQ" src="'.IMGDIR.'/qq.gif" alt="QQ" /> '.$query['qq'].'</a>';
						}
					}
					$s .= '</div>';
				}
			} else {
				$s='未认证领队'.$val;
			}
		}
	} else if ($type=='radio') {
		$arr = array(1=>'Yes', 0=>'No');
		$val = $userval;
		if(empty($val)) $val = $defval;
		if(empty($val)) $val = 0;
		$s = $arr[$val];
	}
	return $s;
}
//页面上显示的用户输入表单
function get_default_field($type, $values, $defval, $propid, $style, $enable, $userval){
	global $_G;
	$type=$type?trim($type):'text';
	$values=$values?trim($values):'';
	$defval=$userval?trim($userval):($defval?trim($defval):'');
	$s = '';
	if($type == 'text' || $type == 'password' || $type == 'number') {
		$s = '<input value="'.($userval?$userval:$values).'" id="'.$propid.'" name="'.$propid.'" type="'.$type.'" class="'.$type.' require_'.$enable.'" onchange="makeEvent(this)" />';
	} else if ($type=='textarea') {
		
		$s = '<textarea rows="6" style="width:99%" id="'.$propid.'" name="'.$propid.'" class="tarea require_'.$enable.'">'.($userval?$userval:$values).'</textarea>';
	} else if ($type=='richtext') {
$s='<div class="editor_tb" ><div class="fpd"><a href="javascript:;" title="Bold" class="fbld" onclick="seditor_insertunit(\''.$propid.'\', \'[b]\', \'[/b]\');doane(event);">B</a><a id="'.$propid.'img" href="javascript:;" title="Image" class="fmg" onclick="seditor_menu(\''.$propid.'\', \'img\');doane(event);">Image</a><a id="'.$propid.'url" href="javascript:;" title="URL" class="flnk" onclick="seditor_menu(\''.$propid.'\', \'url\');doane(event);">Link</a><a id="'.$propid.'quote" href="javascript:;" title="Quote" class="fqt" onclick="seditor_menu(\''.$propid.'\', \'quote\');doane(event);">Quote</a><a id="'.$propid.'code" href="javascript:;" title="Code" class="fcd" onclick="seditor_menu(\''.$propid.'\', \'code\');doane(event);">Code</a></div><textarea id="'.$propid.'message" name="'.$propid.'message" rows="5" cols="80" class=" '.$style.' wd richtxtarea txtarea" tabindex="1" onKeyDown="seditor_ctlent(event, \'fastpostvalidate($(\\\'fastpostform\\\'))\');" >'.($userval?$userval:$values).'</textarea></div>';
	} else if ($type=='select'||$type=='selects') {
		$s = '<div id="'.$propid.'_defval_div"><select id="'.$propid.'_defval" name="'.$propid.'_defval" class="'.$style.' wd require_'.$enable.'" onchange="makeEvent(this)" >';
		foreach(explode("\n", $values) as $key => $option) {
			$option = trim($option);
			if(strpos($option, '=') === FALSE) {
				//$key = $option;
			} else {
				$item = explode('=', $option);
				$key = trim($item[0]);
				$option = trim($item[1]);
			}
			$s .= '<option value="'.$key.'"'.($defval == $key ? 'selected="selected"' : '').'>'.$option.'</option>';
		}
		$s .= '</select><button type="button" class="Modify" value="Modify" onclick="switchValue(\''.$propid.'\')">Modify</button></div><div id="'.$propid.'_value_div" style="display:none">每行一个选项，格式：1=小培<br/><textarea rows="6" id="'.$propid.'_value" name="'.$propid.'_value" cols="50" class="wd tarea">'.$values.'</textarea><button type="button" class="OK" value="OK" onclick="setList(\''.$propid.'\')">OK</button></div>';
	} else if ($type=='credit') {
		$s = '<select id="'.$propid.'" name="'.$propid.'" class="'.$style.' width100 require_'.$enable.'">';
		foreach($_G['setting']['extcredits'] as $key => $option) {
			$s .= '<option value="'.$key.'"'.($defval == $key ? 'selected="selected"' : '').'>'.$option['title'].'</option>';
		}
		$s .= '</select>';
	} else if ($type=='pay'){
		$s .= '<ul class="vtop pay rowform"><li><label><input disabled="disabled" name="'.$propid.'" id="'.$propid.'" type="checkbox" checked="checked" value="pay_under">线下支付</label></li><li><label><input disabled="disabled" name="'.$propid.'" id="'.$propid.'" type="checkbox" value="pay_alipay">支付宝</label></li><li><label><input disabled="disabled" name="'.$propid.'" id="'.$propid.'" type="checkbox" value="pay_credit">积分支付</label></li><li><label><input disabled="disabled" name="'.$propid.'" id="'.$propid.'" type="checkbox" value="pay_tenpay">财付通</label></li></ul>';
/*
		$paylang=array('pay_alipay'=>'支付宝','pay_credit'=>'积分支付','pay_tenpay'=>'财付通','pay_under'=>'线下支付');
		$s='<ul class="vtop pay rowform">';
		//SELECT skey, svalue FROM `cdb_donkey_activity_setting` WHERE skey in ('pay_alipay', 'pay_credit', 'pay_tenpay', 'pay_under')
		$query = DB::query('SELECT skey, svalue FROM '.DB::table('donkey_activity_setting')." WHERE skey in ('pay_alipay', 'pay_credit', 'pay_tenpay', 'pay_under')");
		while($group = DB::fetch($query)) {
			$s .= '<li><label><input name="'.$propid.'" id="'.$group['skey'].'" type="checkbox" value="'.$group['skey'].'">'.$paylang[$group['skey']].'</label></li>';
		}
		$s .= '</ul>';
*/
	} else if ($type=='leader'){
		$l=$userval?$userval:$values;
		if(!empty($l)){
			if(is_numeric($l)){
				$query = DB::fetch_first('SELECT username FROM '.DB::table('common_member').' WHERE uid IN ('.$l.')');
				$u=$query['username'];
			}
			if(empty($u)){
				$u=$l;
			}
		}
		
		$s = '<input type="hidden" id="'.$propid.'" name="'.$propid.'" value="'.$l.'" /><input onchange="resetLeader(this, \''.$propid.'\')" type="text" id="'.$propid.'_disp" value="'.$u.'" /><select id="'.$propid.'_select" class="width100 '.$style.'" onchange="setLeader(this, \''.$propid.'\')"><option value="">非认证领队</option>';
		$groupid=unserialize($_G['cache']['plugin']['donkey_activity']['activity_leader']);
		if(empty($groupid)){
			$groupid = DB::fetch_first('SELECT value FROM '.DB::table('common_pluginvar').' WHERE variable=\'activity_leader\'');	// and pluginid=\''.$pluginid.'\'
			if(!empty($groupid) && !empty($groupid['value'])){
				$groupid=unserialize($groupid['value']);
			}
		}
		if(!empty($groupid)){
			$query = DB::query('SELECT uid, username FROM '.DB::table('common_member').' WHERE groupid IN ('.implode(', ', $groupid).')');
			
			while($group = DB::fetch($query)) {
				$s .= '<option username="'.$group['username'].'" value="'.$group['uid'].'"'.($defval == $group['uid'] ? 'selected="selected"' : '').'>(认证)'.$group['username'].'</option>';
			}
			$s .= '</select>';
		}
	} else if ($type=='date'){
		$s = '<input type="text" id="'.$propid.'" name="'.$propid.'" class="'.$type.' txt require_'.$enable.'" value="'.($userval?$userval:$values).'" onclick="showcalendar(event, this)" />';
	} else if ($type=='datetime'){
		$s = '<input type="text" id="'.$propid.'" name="'.$propid.'" class="'.$type.' txt require_'.$enable.'" value="'.($userval?$userval:$values).'" onclick="showcalendar(event, this, 1)" />';
	} else if ($type=='radio') {
		$s = get_default_radio($defval, $propid, array(1=>'Yes', 0=>'No'));
	} else if ($type=='city') {
		$s = '<input type="hidden" id="districtsetting" value="'.$propid.'"><input type="hidden" id="'.$propid.'" name="'.$propid.'" value="'.($userval?$userval:$values).'">'.$values.'<p id="birthdistrictbox">'.($userval?$userval:$values).'</p><div class="rq mtn" id="showerror_birthcity"></div><p class="d"></p>';
		if($userval || $values){
			$s .= '(<a href="javascript:;" onclick="showdistrict(\'birthdistrictbox\', [\'birthprovince\', \'birthcity\', \'birthdist\', \'birthcommunity\'], 4); return false;">修改</a>)';
		} else {
			$s .= '<script type="text/javascript">showdistrict(\'birthdistrictbox\', [\'birthprovince\', \'birthcity\', \'birthdist\', \'birthcommunity\'], 4);</script>';
		}
/*
$query = DB::query('SELECT id, name FROM '.DB::table('common_district').' WHERE upid=0 ORDER BY displayorder');
		$s = '<input type="hidden" id="'.$propid.'" name="'.$propid.'"><div id="district"><select id="province" onchange="changeCity(this, \''.$propid.'\')" class="'.$style.' wd require_'.$enable.'">';
		while($value = DB::fetch($query)) {
			$s .= '<option value="'.$value['id'].'">'.$value['name'].'</option>';
		}
		$s .= '</select></div>';
*/
	}
	return $s;
}

function get_default_enable($defval, $propid){
/*
三个地方要考虑：后台管理，前台发帖，前台浏览
前台查看时出现(<2)：0, 1
前台查看页面包含(<3)：0, 1, 2
前台发帖时出现(<3)：0, 1, 2
前台发帖页面包含(<4)：0, 1, 2, 3
*/

	$s='<select class="width100" name="'.$propid.'_enable" >';
	$values=array(0=>'默认选填', 1=>'必须填写', 2=>'发帖时显示,查看时隐藏', 3=>'发帖查看时都隐藏', 4=>'不可用只在后台出现', 5=> '前后台都不出现');
	foreach($values as $key => $option) {
		$s .= '<option value="'.$key.'"'.($defval == $key ? 'selected="selected"' : '').'>'.$option.'</option>';
	}
	return $s.'</select>';
}

function get_default_radio($defval, $propid, $values){
	$s='<ul class="vtop width100 rowform">';
	foreach($values as $k => $v) {
		$s .= '<li><label><input class="radio" type="radio" name="'.$propid.'" value="'.$k.'" '.($defval==$k?'checked="checked"':'').'>&nbsp;'.$v.'</label></li>';
	}
	return $s.'</ul>';
}
?>